package io.gitee.twoke.generator.engine.impl.cmd;

import io.gitee.twoke.generator.engine.impl.interceptor.Command;
import io.gitee.twoke.generator.engine.impl.interceptor.CommandContext;
import io.gitee.twoke.generator.engine.impl.persistence.entity.TemplateGroupEntity;
import io.gitee.twoke.generator.engine.impl.template.TemplateGroup;
import io.gitee.twoke.generator.engine.impl.template.impl.CreateTemplateGroupBuilderImpl;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;

import java.util.List;

public class CreateTemplateGroupCmd implements Command<TemplateGroup> {

    private CreateTemplateGroupBuilderImpl createTemplateGroupBuilder;

    public CreateTemplateGroupCmd(CreateTemplateGroupBuilderImpl createTemplateGroupBuilder) {
        this.createTemplateGroupBuilder = createTemplateGroupBuilder;
    }

    @Override
    public TemplateGroup execute(CommandContext commandContext) {
        TemplateGroupEntity templateGroup = createTemplateGroupBuilder.getTemplateGroup();
        if (StrUtil.isBlank(templateGroup.getName())) {
            throw new IllegalArgumentException("template group name is empty");
        }
        commandContext.getTemplateGroupEntityManager().insert(templateGroup);
        List<String> templateIds = createTemplateGroupBuilder.getTemplateIds();
        if (CollectionUtil.isNotEmpty(templateIds)) {
            commandContext.getTemplateGroupEntityManager().saveTemplateGroupRelation(templateIds, templateGroup.getId());
        }
        return templateGroup;
    }

}
